package net.ch2.pc12.tech.ackborn.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class HttpUtils {

	
	public static SimpleHttpResponse sendSimpleRequest(String httpMethod,String url,Map<String,String> params,Map<String,String> headers){

		String ret = "";
		
		SimpleHttpResponse res = new SimpleHttpResponse();
		
        final HttpClient client = new DefaultHttpClient();
        
        final HttpGet get = new HttpGet(url);
        Set<String> set = headers.keySet();
        

        Iterator<String> it = set.iterator();
        while(it.hasNext()){
        	String key = it.next();
        	get.setHeader(key,headers.get(key));
        }
        get.addHeader("Accept-Encoding", "gzip,deflate");
        
		try {
			HttpResponse response = client.execute(get);
			
	        int status = response.getStatusLine().getStatusCode();
			res.setResponseCode(status);
			
			if(status == 200){
				final HttpEntity entity = response.getEntity();
				Header[] heads = response.getHeaders("Content-Encoding");
				boolean zipped = false;
				for(int i=0;i<heads.length;i++){
					if(heads[i].getValue().equals("gzip")){
						zipped = true;
						break;
					}
				}
				if(zipped){
					GZIPInputStream zip = new GZIPInputStream(entity.getContent());
					BufferedReader reader = new BufferedReader(new InputStreamReader(zip,"Shift_JIS"));
					String l;
					while((l = reader.readLine()) != null){
						ret+=l+"\n";
					}
				}else{
					ret = EntityUtils.toString(entity, "Shift_JIS");
				}
		        res.setResponseString(ret);
		        

			}else{
				res.setResponseString(response.getStatusLine().getReasonPhrase());
			}
	        
	        
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return res;
		
	}
	
}
